﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ebc.componentbinder
{
    internal class OutputPin
    {
        private const string EVENT_PREFIX = "On";

        private readonly object component;
        private readonly EventInfo eventInfo;


        public OutputPin(object component, EventInfo eventInfo)
        {
            this.component = component;
            this.eventInfo = eventInfo;
        }


        public Type ComponentType
        {
            get
            {
                return this.component.GetType();
            }
        }


        public Type ParameterType
        {
            get { return DelegateAnalysis.GetDelegateParameterTypes(eventInfo.EventHandlerType).First(); }
        }


        public string PinName
        {
            get
            {
                if (eventInfo.Name.StartsWith(EVENT_PREFIX, StringComparison.InvariantCultureIgnoreCase))
                    return eventInfo.Name.Substring(EVENT_PREFIX.Length);
                return "";
            }
        }


        public void AddEventHandler(Delegate eventHandler)
        {
            this.eventInfo.AddEventHandler(this.component, eventHandler);
        }


        public override bool Equals(System.Object obj)
        {
            if (obj == null) return false;

            OutputPin op = obj as OutputPin;
            if (op == null) return false;

            return this.component == op.component &&
                   this.ParameterType == op.ParameterType &&
                   this.PinName == op.PinName;
        }


        public override string ToString()
        {
            return string.Format("Out: {0}.[On]{1}({2})", this.ComponentType.FullName, this.PinName, this.ParameterType.FullName);
        }
    }
}
